package com.codeoss.framework.webide.app.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.impexp.ExportManager;
import com.codeoss.framework.impexp.ImportManager;
import com.codeoss.framework.webide.app.service.CommonAppDataHandler;
import com.codeoss.module.ir.model.IrApplication;
import com.codeoss.module.ir.model.IrDocType;
import com.codeoss.module.ir.service.IIrDocTypeService;

@Service("ir_doc_typeAppDataHandler")
public class IrDocTypeAppDataHandler extends CommonAppDataHandler {
    @Autowired
    private IIrDocTypeService irDocTypeService;
    @Autowired
    private ExportManager exportManager;
    @Autowired
    private ITableStore tableStore;
    @Autowired
  	private ImportManager importManager;
	@Override
	public void dataExport(YunContext yunContext, IrApplication irApplication, String tableName) throws IOException{
		// TODO Auto-generated method stub
		QueryWrapper<IrDocType> queryWrapper=new QueryWrapper<IrDocType>();
		queryWrapper.in("module_type", getModuleTypeList(yunContext, irApplication));
		queryWrapper.orderByAsc("id");
		List<IrDocType> irDocTypeList=irDocTypeService.list(queryWrapper);
		for (int i = 0; i < irDocTypeList.size(); i++) {
			IrDocType irDocType=irDocTypeList.get(i);
			Table table=tableStore.get("ir_doc_type");
			Query query=new Query();
			query.add(Restrictions.eq("code", irDocType.getCode()));
			String filename="ir_doc_type"+i;
			writeConfigKeyValue(yunContext, "ir_doc_type", filename);
			FileOutputStream os=createFileOutputStream(yunContext, filename);
			exportManager.exportProperties(yunContext, table, query, os);
			os.close();
		}
	}

	@Override
	@Transactional
	public void dataImport(YunContext yunContext, IrApplication irApplication, String tableName, List<String> filenameList)throws IOException {
		// TODO Auto-generated method stub
		if (filenameList == null) {
			return;
		}
		for(int i=0;i<filenameList.size();i++) {
			String filename=filenameList.get(i);
			InputStream is=createFileInputStream(yunContext, filename);
			Table table = tableStore.get("ir_doc_type");
			importManager.importProperties(yunContext, table, is);
			is.close();
		}
	}

}
